package com.jx.mlxg.controller;

import com.jx.mlxg.common.BusinessException;
import com.jx.mlxg.common.ExceptionEnum;
import com.jx.mlxg.entity.Addresses;
import java.util.List;
import com.jx.mlxg.entity.Orders;
import com.jx.mlxg.service.OrdersService;
import com.jx.mlxg.utils.PageResponse;
import com.jx.mlxg.utils.ResponseResult;
import com.jx.mlxg.utils.UserOrderStatisticsResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Map;

/**
* 订单相关
* */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Resource
    private OrdersService ordersService;

    /**
    * 订单列表
    * */
    @PostMapping("/list")
    public ResponseResult<PageResponse<Orders>> listOrders(
//            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
//            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestBody Map<String, Object> filterParams) {
        try {
            Integer pageNo = (Integer) filterParams.get("pageNo");
            Integer pageSize = (Integer) filterParams.get("pageSize");
            PageResponse<Orders> pageResponse = ordersService.listOrders(pageNo, pageSize, filterParams);
            return ResponseResult.success(pageResponse);
        } catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        }
    }

    /**
     * 根据用户名查询订单列表
     * */
    @GetMapping("/list/{username}")
    public ResponseResult<PageResponse<Orders>> listOrdersByUsername(
            @PathVariable String username,
            @RequestParam(value = "pageNo", defaultValue = "1") int pageNo,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        try {
            PageResponse<Orders> pageResponse = ordersService.listOrdersByUsername(username, pageNo, pageSize);
            return ResponseResult.success(pageResponse);
        } catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        }
    }

    /**
     * 根据订单id查询订单详情
     * */
    @PostMapping("/detail")
    public ResponseResult<Orders> getOrderById(@RequestBody Map orderMap) {
        try {
            String orderId = (String) orderMap.get("orderId");
            String openId = SecurityContextHolder.getContext().getAuthentication().getName();

            Orders order = ordersService.getOrderById(orderId, openId);
            return ResponseResult.success(order);
        } catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        }
    }

    @GetMapping("/delete")
    public ResponseResult<Integer> deleteOrderById() {
        int i = ordersService.selectByStatus();
        return ResponseResult.success(i);
    }

    /**
     * 获取用户订单统计数据
     * @param filterParams 过滤参数，包含timeDimension、startTime、endTime等
     * @return 订单统计响应
     */
    @PostMapping("/statistics")
    public ResponseResult<UserOrderStatisticsResponse> getUserOrderStatistics(@RequestBody Map<String, Object> filterParams) {
        try {
            // 从filterParams中获取时间维度参数
            String timeDimension = (String) filterParams.get("timeDimension");
            Long startTime = filterParams.get("startTime") != null ? Long.parseLong(filterParams.get("startTime").toString()) : null;
            Long endTime = filterParams.get("endTime") != null ? Long.parseLong(filterParams.get("endTime").toString()) : null;

            log.info("【订单统计接口】收到请求，时间维度：{}", timeDimension);
            UserOrderStatisticsResponse response = ordersService.getUserOrderStatistics(timeDimension, startTime, endTime);
            return ResponseResult.success(response);
        } catch (BusinessException e) {
            log.warn("【业务异常】订单统计失败，错误码：{}", e.getCode());
            return ResponseResult.failure(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("【系统异常】订单统计错误，异常类型：{}", e.getClass().getSimpleName());
            return ResponseResult.failure(500, "系统内部错误");
        }
    }
    
    /**
     * 更新订单关联的地址ID
     * @param orderId 订单ID
     * @param addressId 地址ID
     * @return 更新结果
     */
    @PostMapping("/update-address")
    public ResponseResult updateOrderAddress(@RequestParam String orderId,
                                            @RequestParam Integer addressId) {
        try {
            boolean result = ordersService.updateOrderAddressId(orderId, addressId);
            return ResponseResult.success(result);
        } catch (BusinessException e) {
            return ResponseResult.failure(e.getCode(), e.getMessage());
        } catch (Exception e) {
            return ResponseResult.failure(ExceptionEnum.UNKNOWN_ERROR.getCode(), e.getMessage());
        }
    }
    
    /**
     * 根据订单ID查询指定人员的地址信息列表
     * @param orderId 订单ID
     * @return 地址信息列表（按创建时间降序排序）
     */
    @GetMapping("/get-address-by-order-id")
    public ResponseResult<List<Addresses>> getAddressByOrderId(@RequestParam String orderId) {
        try {
            log.info("【订单地址查询接口】收到请求，订单ID：{}", orderId);
            List<Addresses> addresses = ordersService.getAddressByOrderId(orderId);
            return ResponseResult.success(addresses);
        } catch (BusinessException e) {
            log.warn("【业务异常】订单地址查询失败，错误码：{}", e.getCode());
            return ResponseResult.failure(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error("【系统异常】订单地址查询错误，异常类型：{}", e.getClass().getSimpleName());
            return ResponseResult.failure(500, "系统内部错误");
        }
    }

}
